<template>
  <view class="uni-container">
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title">授标管理</view>
      </view>
    </view>
    
    <view class="uni-forms">
      <view class="uni-forms-item">
        <view class="uni-forms-item-label">采购单名称</view>
        <view class="uni-forms-item-value">{{ auctionData.title }}</view>
      </view>
      
      <view class="uni-forms-item">
        <view class="uni-forms-item-label">采购单编号</view>
        <view class="uni-forms-item-value">{{ auctionData.serial_number }}</view>
      </view>
      
      <view class="uni-forms-item">
        <view class="uni-forms-item-label">当前状态</view>
        <view class="uni-forms-item-value">{{ statusText }}</view>
      </view>
      
      <view class="uni-forms-item" v-if="auctionData.status === 'bidding'">
        <view class="uni-forms-item-label">截止时间</view>
        <view class="uni-forms-item-value">
          <uni-dateformat :threshold="[0, 0]" :date="auctionData.end_time"></uni-dateformat>
        </view>
      </view>
      
      <view class="uni-forms-item">
        <view class="uni-forms-item-label">起始价格</view>
        <view class="uni-forms-item-value">￥{{ auctionData.start_price }}</view>
      </view>
      
      <view class="uni-forms-item" v-if="bidsList.length > 0">
        <view class="uni-forms-item-label">报价列表</view>
        <view class="uni-forms-item-value">
          <uni-table border stripe>
            <uni-tr>
              <uni-th>供应商</uni-th>
              <uni-th>报价金额</uni-th>
              <uni-th>报价时间</uni-th>
              <uni-th>操作</uni-th>
            </uni-tr>
            <uni-tr v-for="(bid, index) in bidsList" :key="index">
              <uni-td>{{ bid.supplier_info ? (bid.supplier_info.nickname || bid.supplier_info.username) : bid.supplier_user_id }}</uni-td>
              <uni-td>￥{{ bid.amount }}</uni-td>
              <uni-td>
                <uni-dateformat :threshold="[0, 0]" :date="bid.timestamp"></uni-dateformat>
              </uni-td>
              <uni-td>
                <button size="mini" type="primary" @click="selectWinner(bid)" :disabled="auctionData.status === 'finished'">选择为中标者</button>
              </uni-td>
            </uni-tr>
          </uni-table>
        </view>
      </view>
      
      <view class="uni-forms-item" v-else>
        <view class="uni-forms-item-label">报价列表</view>
        <view class="uni-forms-item-value">暂无报价</view>
      </view>
      
      <view class="uni-forms-item" v-if="auctionData.winner_supplier_id">
        <view class="uni-forms-item-label">中标供应商</view>
        <view class="uni-forms-item-value">
          {{ winnerSupplierInfo ? (winnerSupplierInfo.nickname || winnerSupplierInfo.username) : auctionData.winner_supplier_id }}
        </view>
      </view>
      
      <view class="uni-forms-item" v-if="auctionData.status === 'bidding'">
        <view class="uni-forms-item-label">操作</view>
        <view class="uni-forms-item-value">
          <button type="warn" @click="finishAuction">结束竞价</button>
        </view>
      </view>
    </view>
    
    <view class="uni-button-group">
      <button class="uni-button" style="width: 100px;" @click="navigateBack">返回</button>
    </view>
  </view>
</template>

<script>
  const db = uniCloud.database();
  const dbCmd = db.command;
  const auctionsCollectionName = 'auctions';
  const bidsCollectionName = 'bids';
  const usersCollectionName = 'uni-id-users';

  export default {
    data() {
      return {
        auctionId: '',
        auctionData: {
          "title": "",
          "serial_number": "",
          "description": "",
          "start_price": 0,
          "end_time": null,
          "attachments": [],
          "status": "bidding",
          "invited_supplier_ids": [],
          "winner_supplier_id": "",
          "create_time": null,
          "finish_time": null
        },
        bidsList: [],
        winnerSupplierInfo: null,
        statusOptions: {
          "bidding": "竞价中",
          "finished": "已结束"
        }
      }
    },
    computed: {
      statusText() {
        return this.statusOptions[this.auctionData.status] || this.auctionData.status;
      }
    },
    onLoad(e) {
      if (e.id) {
        this.auctionId = e.id
        this.getAuctionDetail()
        this.getBidsList()
      }
    },
    methods: {
      /**
       * 获取采购单详情
       */
      getAuctionDetail() {
        uni.showLoading({
          mask: true
        })
        db.collection(auctionsCollectionName).doc(this.auctionId).get().then(async (res) => {
          const data = res.result.data[0]
          if (data) {
            this.auctionData = data
            
            // 如果已有中标供应商，获取供应商信息
            if (data.winner_supplier_id) {
              await this.getWinnerSupplierInfo(data.winner_supplier_id)
            }
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
      
      /**
       * 获取中标供应商信息
       */
      async getWinnerSupplierInfo(supplierId) {
        try {
          const res = await db.collection(usersCollectionName).doc(supplierId).get()
          const userData = res.result.data[0]
          if (userData) {
            this.winnerSupplierInfo = userData
          }
        } catch (err) {
          console.error('获取中标供应商信息失败:', err)
        }
      },
      
      /**
       * 获取报价列表
       */
      getBidsList() {
        db.collection(bidsCollectionName)
          .where(`auction_id == "${this.auctionId}"`)
          .orderBy('amount asc') // 按报价金额升序排列
          .get()
          .then(async (res) => {
            const bids = res.result.data || []
            // 获取每个报价的供应商信息
            for (let i = 0; i < bids.length; i++) {
              try {
                const userRes = await db.collection(usersCollectionName).doc(bids[i].supplier_user_id).get()
                const userData = userRes.result.data[0]
                if (userData) {
                  bids[i].supplier_info = userData
                }
              } catch (err) {
                console.error('获取供应商信息失败:', err)
              }
            }
            this.bidsList = bids
          }).catch((err) => {
            uni.showModal({
              content: '获取报价列表失败: ' + err.message,
              showCancel: false
            })
          })
      },
      
      /**
       * 选择中标者
       */
      selectWinner(bid) {
        uni.showModal({
          title: '确认授标',
          content: `确定要将此采购单授予供应商 ${bid.supplier_info ? (bid.supplier_info.nickname || bid.supplier_info.username) : bid.supplier_user_id} 吗？`,
          success: (res) => {
            if (res.confirm) {
              this.setWinner(bid.supplier_user_id)
            }
          }
        })
      },
      
      /**
       * 设置中标者
       */
      setWinner(supplierUserId) {
        uni.showLoading({
          mask: true
        })
        db.collection(auctionsCollectionName).doc(this.auctionId).update({
          winner_supplier_id: supplierUserId
        }).then((res) => {
          uni.showToast({
            title: '授标成功'
          })
          this.auctionData.winner_supplier_id = supplierUserId
          this.getWinnerSupplierInfo(supplierUserId)
        }).catch((err) => {
          uni.showModal({
            content: '授标失败: ' + err.message,
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
      
      /**
       * 结束竞价
       */
      finishAuction() {
        // 检查是否已到截止时间或手动结束
        const now = Date.now()
        if (this.auctionData.end_time && now < this.auctionData.end_time) {
          uni.showModal({
            title: '提示',
            content: '还未到截止时间，确定要提前结束竞价吗？',
            success: (res) => {
              if (res.confirm) {
                this.doFinishAuction()
              }
            }
          })
        } else {
          this.doFinishAuction()
        }
      },
      
      /**
       * 执行结束竞价操作
       */
      doFinishAuction() {
        uni.showLoading({
          mask: true
        })
        db.collection(auctionsCollectionName).doc(this.auctionId).update({
          status: 'finished',
          finish_time: Date.now()
        }).then((res) => {
          uni.showToast({
            title: '竞价已结束'
          })
          this.auctionData.status = 'finished'
          this.auctionData.finish_time = Date.now()
        }).catch((err) => {
          uni.showModal({
            content: '结束竞价失败: ' + err.message,
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      },
      
      /**
       * 返回上一页
       */
      navigateBack() {
        uni.navigateBack()
      }
    }
  }
</script>

<style scoped>
.uni-forms-item {
  display: flex;
  flex-direction: column;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.uni-forms-item-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.uni-forms-item-value {
  color: #333;
}

.uni-button-group {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}
</style>